package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@CrossOrigin
@RestController
public class TokenController {

    @Autowired
    private RedisTokenStore redisTokenStore;
    /**
     * 获取当前token对应的用户主体的凭证信息(认证对象)
     */
    @GetMapping("/user")
    public OAuth2Authentication getAuth(@RequestParam(value = "access_token",required = false) String token,HttpServletRequest request) {
        String authorization =request.getHeader("Authorization");
        if(authorization!=null&&authorization!="")
        {
            String[] authorizations=authorization.split(" ");
            if(authorizations.length==2)
                token=authorizations[1];
        }
        TokenStore tokenStore = (TokenStore) redisTokenStore;
        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
        return oAuth2Authentication;
    }

    @GetMapping("/me")
    public Principal me(Principal principal) {
        return principal;
    }

    /**
     * 覆盖了 spring-security-oauth2 内部的 endpoint oauth2/check_token
     * spring-security-oauth2 内部原有的该控制器 CheckTokenEndpoint，返回值，不符合自身业务要求，故覆盖之。
     */
    @GetMapping("/check_token")
    public OAuth2AccessToken getToken(@RequestParam(value = "token",required = false) String token,HttpServletRequest request){
        TokenStore tokenStore = (TokenStore) redisTokenStore;
        OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
        return oAuth2AccessToken;
    }
}
